<?php

    class Cicp_GraphManager
{
    private $_graphs = array();

    function __construct()
    {
    }

    /**
     * saves all graphs before being destroyed
     */ 
    function __destruct()
    {
        $this->saveGraphs();
    }

    /**
     * calls storage driver for each graph to save it permanently
     */
    function saveGraphs()
    {
        foreach ($this->_graphs as $graph) {
            Cicp::getInstance()->getStorageDriver()->storeGraph($graph);
        }
    }

    /**
     * deletes cicp graph $graph and calls storage driver to remove
    the permanent representation
    */
    function deleteGraph(Cicp_Graph $graph)
    {
        Cicp::getInstance()->getStorageDriver()->deleteGraph($graph);
        unset($this->_graphs[$graph->getId()]);
    }

    /**
     * returns graph with graph id $graphId 
     */
    function getGraph($graphId)
    {
        return $this->loadGraph($graphId);
    }

    /** 
     * registers a graph
     */
    function registerGraph(Cicp_Graph $graph)
    { 
        // check if already registered
        if (!array_key_exists($graph->getId(), $this->_graphs)) {
            $this->_graphs[$graph->getId()] = $graph;
        }
        return $graph;
    }

    /**
     * calls storage driver to load graph with graph id $graphid and
    returns it
    */
    function loadGraph($graphId)
    {
        // check if graph not already loaded
        if (isset($this->_graphs[$graphId])) {
            return $this->_graphs[$graphId];
        }
        else { // read from storage
            $graph = Cicp::getInstance()->getStorageDriver()->readGraph($graphId);
            if ($graph instanceof Cicp_Graph) {
                $this->_graphs[$graphId] = $graph;
                return $graph;
            }
            else {
                throw new Exception('Graph ' . $graphId
                                    . ' does not exist.');
            }
        }
    }

}